<?php

namespace app\admin\controller\scanwork;

use app\common\controller\Backend;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 工厂管理
 *
 * @icon fa fa-building
 * @remark 管理分厂信息和权限
 */
class Factory extends Backend
{
    /**
     * Factory模型对象
     * @var \app\admin\model\scanwork\Factory
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\scanwork\Factory;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['userFactories.user'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                // 检查工厂编码是否唯一
                if (!$this->model->checkCodeUnique($params['code'])) {
                    $this->error('工厂编码已存在');
                }

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            } else {
                $this->error(__('Parameter %s can not be empty', ''));
            }
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                // 检查工厂编码是否唯一
                if (!$this->model->checkCodeUnique($params['code'], $ids)) {
                    $this->error('工厂编码已存在');
                }
                
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $name;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            } else {
                $this->error(__('Parameter %s can not be empty', ''));
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $item) {
                    // 检查是否有关联数据
                    $this->checkFactoryRelations($item->id);
                    
                    $count += $item->delete();
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        } else {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
    }

    /**
     * 检查工厂关联数据
     */
    private function checkFactoryRelations($factoryId)
    {
        // 检查是否有产品
        $productCount = \app\admin\model\scanwork\Product::where('factory_id', $factoryId)->count();
        if ($productCount > 0) {
            throw new Exception("该工厂下还有{$productCount}个产品，请先删除相关产品");
        }

        // 检查是否有订单
        $orderCount = \app\admin\model\scanwork\Order::where('factory_id', $factoryId)->count();
        if ($orderCount > 0) {
            throw new Exception("该工厂下还有{$orderCount}个订单，请先删除相关订单");
        }

        // 检查是否有用户关联
        $userCount = \app\admin\model\scanwork\UserFactory::where('factory_id', $factoryId)->count();
        if ($userCount > 0) {
            throw new Exception("该工厂下还有{$userCount}个用户关联，请先删除相关用户关联");
        }
    }

    /**
     * 工厂用户管理
     */
    public function users($ids = null)
    {
        $factory = $this->model->get($ids);
        if (!$factory) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isAjax()) {
            $list = \app\admin\model\scanwork\UserFactory::with(['user'])
                ->where('factory_id', $ids)
                ->select();
            
            $result = array("total" => count($list), "rows" => $list);
            return json($result);
        }

        $this->view->assign('factory', $factory);
        return $this->view->fetch();
    }

    /**
     * 添加用户到工厂
     */
    public function addUser()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                // 检查用户是否已关联该工厂
                $exists = \app\admin\model\scanwork\UserFactory::where([
                    'user_id' => $params['user_id'],
                    'factory_id' => $params['factory_id']
                ])->find();
                
                if ($exists) {
                    $this->error('该用户已关联此工厂');
                }

                $result = \app\admin\model\scanwork\UserFactory::create($params);
                if ($result) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            } else {
                $this->error(__('Parameter %s can not be empty', ''));
            }
        }

        $factoryId = $this->request->get('factory_id');
        $factory = $this->model->get($factoryId);
        
        // 获取未关联的用户列表
        $linkedUserIds = \app\admin\model\scanwork\UserFactory::where('factory_id', $factoryId)->column('user_id');
        $userList = \app\common\model\User::where('status', 'normal')
            ->where('id', 'not in', $linkedUserIds)
            ->column('nickname', 'id');
        
        $this->view->assign('factory', $factory);
        $this->view->assign('userList', $userList);
        $this->view->assign('roleList', \app\admin\model\scanwork\UserFactory::getRoleList());
        return $this->view->fetch();
    }

    /**
     * 移除工厂用户
     */
    public function removeUser($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $count = \app\admin\model\scanwork\UserFactory::where('id', 'in', $ids)->delete();
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        } else {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
    }

    /**
     * 获取工厂列表（用于下拉选择）
     */
    public function getFactoryList()
    {
        $list = $this->model->where('status', 1)->column('name', 'id');
        $this->success('', null, $list);
    }
}
